package com.junxonline.instant.api.handler;

import com.junxonline.instant.common.entity.common.CommonResult;
import com.junxonline.instant.common.enumeration.ApiErrorEnum;
import com.junxonline.instant.common.exception.ApiBizException;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * API服务异常处理
 *
 * @author JunX
 * @date 2021-09-15
 */
@Log4j2
@ControllerAdvice
@RestController
public class ApiBizExceptionHandler {

    /**
     * 请求类型异常处理
     *
     * @param e e
     * @return CommonResult
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public CommonResult httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
        log.error("请求发生异常 => {}", e.getMethod());
        return CommonResult.fail(ApiErrorEnum.REQUEST_TYPE_NOT_SUPPORT);
    }

    /**
     * 断言异常处理
     *
     * @param e e
     * @return CommonResult
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public CommonResult illegalArgumentExceptionHandler(IllegalArgumentException e) {
        log.error("系统发生断言异常 => ", e);
        return CommonResult.fail(ApiErrorEnum.ASSERT_ERROR.getCode(), e.getMessage());
    }

    /**
     * 业务异常处理
     *
     * @param e e
     * @return CommonResult
     */
    @ExceptionHandler(value = ApiBizException.class)
    public CommonResult apiBizExceptionHandler(ApiBizException e) {
        log.error("系统发生业务异常 => {}", e.getMsg());
        return CommonResult.fail(e.getCode(), e.getMsg());
    }

    /**
     * 其它异常处理
     *
     * @param e e
     * @return CommonResult
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResult exceptionHandler(Exception e) {
        log.error("系统发生异常 => ", e);
        return CommonResult.fail(ApiErrorEnum.INTERNAL_SERVER_ERROR);
    }

}
